package 动态数组.队列;

import 动态数组.栈.ArrayStack;

/**
 * 栈实现队列
 */
public class StackToQueue {
    public static void main(String[] args) {
        QueueImplByStack<Integer> stack = new QueueImplByStack<>();
        for (int i = 1; i <= 4; i++) {
            stack.offer(i);
        }
        System.out.println(stack);
        System.out.println(stack.poll());
        System.out.println(stack.poll());
        System.out.println(stack);
        System.out.println(stack.peek());
    }
}

class QueueImplByStack<E>{
    private ArrayStack<E> stackA;
    private ArrayStack<E> stackB;

    public QueueImplByStack(){
        stackA = new ArrayStack<>();
        stackB = new ArrayStack<>();
    }

    public void offer(E e){
        stackA.push(e);
    }

    public E poll(){
        while (!stackA.isEmpty()){
            stackB.push(stackA.pop());
        }
        E ret = stackB.pop();
        while (!stackB.isEmpty()){
            stackA.push(stackB.pop());
        }
        return ret;
    }

    public E peek(){
        while (!stackA.isEmpty()){
            stackB.push(stackA.pop());
        }
        E ret = stackB.peek();
        while (!stackB.isEmpty()){
            stackA.push(stackB.pop());
        }
        return ret;
    }

    @Override
    public String toString() {
        return stackA.toString();
    }
}
